﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace _15_Task_多线程
{
    public partial class Form1 : Form
    {
        ManualResetEvent resetEvent = null;
        CancellationTokenSource cts = null;

        public Form1()
        {
            InitializeComponent();
            //取消跨线程访问检查
            CheckForIllegalCrossThreadCalls = false;
        }


        public void DoWork()
        {
            for (int i = 0; i <= 100; i++)
            {
                if (cts.IsCancellationRequested)
                {
                    return;
                }

                //判断是否挂起
                resetEvent.WaitOne();

                //更新进度
                this.progressBar1.Value = i;
                //更新文本
                this.label2.Text = i + "%";

                Thread.Sleep(100);
            }
        }
        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            resetEvent = new ManualResetEvent(true);
            cts = new CancellationTokenSource();

            Task.Run(DoWork);
        }
        /// <summary>
        /// 线程挂起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            resetEvent.Reset();
        }
        /// <summary>
        /// 线程唤醒
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            resetEvent.Set();
        }
        /// <summary>
        /// 线程终止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            cts.Cancel();
        }
    }
}
